<template>
  <el-form label-position="top" label-width="100px" :model="articleFrom" style="max-width: 90%;" :rules="rules"
    ref="articleRef">
    <el-form-item label="标题" prop="title">
      <el-input v-model="articleFrom.title" />
    </el-form-item>
    <el-form-item label="内容" prop="articleHTML">
      <WangEditor :articleHTML="articleFrom.articleHTML" @setArticleHTML="setArticleHTML"></WangEditor>
    </el-form-item>
  </el-form>
  <el-button @click="submitForm('articleRef')">提交</el-button>
</template>

<script setup>
import WangEditor from '@/components/WangEditor.vue'
import { reactive, ref, onMounted, getCurrentInstance } from 'vue'
import { ElMessage } from "element-plus";
import { SubmitArticle } from '@/api.js'
const internalInstance = getCurrentInstance();
const articleFrom = ref({
  title: '',
  articleHTML: ''
})
const articleRef = ref(null)
onMounted(() => {

})

const validateContent = (rule, value, callback) => {
  if (value === '<p><br></p>') {
    callback(new Error('请输入内容'))
  } else {
    callback()
  }
}
const rules = reactive({
  title: { required: true, message: '请输入正确的标题', trigger: 'blur' },
  articleHTML: { validator: validateContent, trigger: 'blur' }

})
const setArticleHTML = (value) => {
  articleFrom.value.articleHTML = value
}
const userInfo = JSON.parse(localStorage.getItem('userInfo'))
const submitForm = async (article) => {
  console.log(internalInstance);
  await internalInstance.ctx.$refs[article].validate((valid, fields) => {
    if (valid) {
      console.log(articleFrom);
      SubmitArticle(articleFrom.value.articleHTML, userInfo.uuid, articleFrom.value.title, '').then(res => {
        if (res.success) {
          ElMessage({
            message: "上传成功",
            type: "success",
          });
          location.reload();
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>

<style>

</style>